package com.boe.csb.core.service.csb;

import com.alibaba.csb.console.sdk.Result;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boe.csb.core.common.CsbConstants;
import com.boe.csb.core.common.status.SubscribeStatusEnum;
import com.boe.csb.core.common.utils.CsbApiCaller;
import com.boe.csb.core.common.utils.MailTemplate;
import com.boe.csb.core.entity.po.BoeUser;
import com.boe.csb.core.service.SendMailService;
import com.boe.csb.core.service.api.BoeApiInfoService;
import com.boe.csb.core.service.api.BoeApiPopularService;
import com.boe.csb.core.service.user.BoeUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by tianxiang.luo on 16/12/4.
 */
@Service("csbAuditOrderService")
public class CsbAuditOrderService {


    private Logger logger  = LoggerFactory.getLogger(CsbAuditOrderService.class);

    //审批
    private static final String APPROVE_ORDER = "/api/order/approve";

    //查看审核列表
    private static final String ORDER_LIST = "/api/order/approvalList";

    //获取单个服务的信息
    private static final String FIND_ORDER = "/api/order/find";


    @Autowired
    private BoeUserService boeUserService;
    @Autowired
    private BoeApiPopularService boeApiPopularService;

    @Autowired
    private BoeApiInfoService boeApiInfoService;

    @Autowired
    private SendMailService sendMailService;

    /**
     * 订单列表
     */
    public Result orderList(String userId, String serviceId, Integer pageNum, Boolean onlyPending, String serviceName,String alias) {
        Map<String, String> queryMap = new HashMap<>();
        queryMap.put("userId", userId);
        queryMap.put("csbId", CsbApiCaller.CSB_ID);
        if (serviceId != null) {
            queryMap.put("serviceId", serviceId);
        }
        if (onlyPending != null) {
            queryMap.put("onlyPending", String.valueOf(onlyPending));
        }
        if (serviceName != null) {
            queryMap.put("serviceName", serviceName);
        }
        if (alias != null){
            queryMap.put("alias", alias);
        }
        queryMap.put("pageNum", pageNum.toString());
        return CsbApiCaller.callCsbGetApi(ORDER_LIST, queryMap);
    }

    /**
     * 用户审核订单
     */
    public Result auditOrder(String userId, JSONObject data) {
        JSONObject order = data.getJSONObject("order");
        String comment = order.getString("comment");
        boolean orderStatus = order.getBoolean("status");
        Long orderId = order.getLong("orderId");
        //拼接成一个订单
        JSONObject o = new JSONObject();
        o.put("id", orderId);
        o.put("orderStatus", orderStatus);
        o.put("comments", comment);
        JSONArray approvalList = new JSONArray();
        approvalList.add(o);
        JSONObject obj = new JSONObject();
        obj.put("approvalList", approvalList);

        Map<String, String> map = new HashMap<>();
        map.put("csbId", CsbApiCaller.CSB_ID);
        map.put("userId", userId);
        Result result = CsbApiCaller.callCsbPostApi(APPROVE_ORDER, map, JSONObject.toJSONString(obj));


        if (result.isSuccess()) {
            Long serviceId = data.getLong("serviceId");
            //更新热门度
            boeApiPopularService.updatePopularBoeApiList(Arrays.asList(serviceId));
            Long subscribeUserId = data.getLong("userId");
            //发送邮件
            String boeApiName = boeApiInfoService.getApiServerNameById(serviceId);
            BoeUser boeUser = boeUserService.findBoeUser(String.valueOf(subscribeUserId));

            String emailContent = MailTemplate.generateServiceAuditMail(orderStatus, boeApiName, "订阅");
            sendMailService.asyncSendMail(boeUser.getEmail(), CsbConstants.SERVICE_AUDIT_MAIL_SUBJECT, emailContent);
        }

        return result;
    }


    public Integer queryOrderStatusByServiceName(String userId, String serviceName) {
        if (userId == null || serviceName == null) {
            return SubscribeStatusEnum.NO_ORDER.getValue();
        } else {
            BoeUser boeUser = boeUserService.findBoeUser(userId);
            if (boeUser!=null && Boolean.TRUE.equals(boeUser.getIsAdmin())) {
                return SubscribeStatusEnum.NO_ORDER.getValue();
            }
            Map<String, String> query = new HashMap<>();
            //发布服务者id
            query.put("userId", userId);
            query.put("csbId", CsbApiCaller.CSB_ID);
            query.put("serviceName", serviceName);
            try {
                Result result = CsbApiCaller.callCsbGetApi(FIND_ORDER, query);
                if (result.isSuccess()) {
                    JSONObject object = result.getData();
                    if (object != null) {
                        JSONObject order = object.getJSONObject("order");
                        if (order != null) {
                            return order.getInteger("status");
                        }
                    }
                }
            }catch (Exception e){
                //csb那边找不到订单抛500 所以就返回给前端null 没有订阅
                logger.info("该用户:id{}没有订购过服务名{}",userId,serviceName,e);
                return SubscribeStatusEnum.NO_ORDER.getValue();
            }
            return SubscribeStatusEnum.NO_ORDER.getValue();
        }
    }
}